package com.uzhie.web.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uzhie.web.bean.PageBean;
import com.uzhie.web.bean.RequestBean;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * Created by TangFei on 2018/7/20.
 * 请求参数处理 剥离请求参数 执行目标方法 捕捉异常
 * 2. 请求参数剥离 向上抛出runtimeException
 */
public class RequestAspect {

    private Logger logger = Logger.getLogger(this.getClass());

    public Object run(ProceedingJoinPoint point) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        Object[] reqArgs = point.getArgs();
        RequestBean requestBean = JSONObject.parseObject(JSON.toJSONString(reqArgs[0]), RequestBean.class);
        try {
            // 如果在下面的代码中抛出异常 则不会执行目标方法 就不会执行 after-throwing 和 after 下面的catch只能捕获到该异常
            // 如果是在目标方法中抛出的异常 则会执行 after-throwing（能捕捉到目标方法的异常） 和 after 下面的catch捕捉的就是目标方法抛出的异常
            Object[] methodArgs = new Object[method.getParameterTypes().length];
            for (int i = 0; i < method.getParameterTypes().length; i++) {
                if (method.getParameterTypes()[i] == JSONObject.class) {
                    methodArgs[i] = requestBean.getRequestBody();
                } else if (method.getParameterTypes()[i] == PageBean.class) {
                    methodArgs[i] = requestBean.getPage();
                } else {
                    continue;
                }
            }
            return point.proceed(methodArgs);
        } catch (RuntimeException e) {
            logger.error("系统发生异常，向上抛出异常", e);
            throw e;
        } finally {
            logger.trace("请求参数剥离完成");
        }
    }

}
